import React, { Component } from 'react';
import {Card, Select, Input, Button, Table, message} from 'antd'
import {PlusCircleOutlined} from '@ant-design/icons'
import {reqProductList, reqSearchProduct, reqProductStatus} from '../../api/api'
import withRouter from '../../utils/withRouter'

const Option = Select.Option


class ProductHome extends Component {

  state = {
    total: 0,
    products: [],
    loading: false,
    searchName: '', // 搜索关键字
    searchType: 'productName'
  }

  // 请求商品列表
  getProductList = async (pageNum=1) => {
    this.pageNum = pageNum //保存一下 更新状态的时候使用
    this.setState ({loading: true})
    const {searchName, searchType} = this.state
    let result
    // 搜索请求
    if (searchName) {
      result = await reqSearchProduct (pageNum, 3, searchType, searchName)
      // console.log (result)
    } else {
      result = await reqProductList (pageNum, 3)
    // console.log (result)
    }
    if (result.status === 0) {
      const {total, list} = result.data
      this.setState ({
        total,
        products: list,
        loading: false
      })
    }
    
  }

  // 更新上架状态
  async updateStatus (productId, status) {
    const result = await reqProductStatus (productId, status)
    if (result.status === 0) {
      message.success('更新商品状态成功')
      this.getProductList (this.pageNum)
    }
  }

  componentDidMount () {
    this.getProductList ()
  }

  UNSAFE_componentWillMount () {
    this.initColumns ()
  }

  initColumns = () => {
    this.columns = [
      {
        title: '商品名称',
        dataIndex: 'name',
      },
      {
        title: '商品描述',
        dataIndex: 'desc',
      },
      {
        title: '价格',
        dataIndex: 'price',
        render: (price) => { // 如果没有指定price 就是当前行对象，指定了就是price
          return `￥${price}`
        }
      },
      {
        title: '状态',
        width: 100,
        render: (product) => { // 如果没有指定price 就是当前行对象，指定了就是price
          const {status, _id} = product
          const newStatus = status===1? 2: 1
          return (
            <span>
              {/* <Button type='primary'>{status===1? '下架': '上架'}</Button> */}
              {product.status===1? <Button type='danger' onClick={()=> {this.updateStatus (_id, newStatus)}}>下架</Button> : 
              <Button type='primary'onClick={()=> {this.updateStatus (_id, newStatus)}}>上架</Button>
              }
              <span>{product.status===1? '在售': '已下架'}</span>
            </span>
          )
        }
      },
      {
        title: '操作',
        width: 100,
        render: (product) => { // 如果没有指定price 就是当前行对象，指定了就是price
          return (
            <span>
              {/* router v6编程式跳转携带 state参数 */}
              <Button type="link" onClick={()=>this.props.navigate('detail', {state: product})}>详情</Button>
              <Button type="link" onClick={()=>this.props.navigate('addupdate',{state: product})}>修改</Button>
            </span>
          )
        }
      },
    ];
  }

  render() {

    const {products,total,loading,searchName} = this.state

    const title = (
      <div>
        <Select defaultValue='productName' onChange={value => this.setState ({searchType: value})}>
          <Option value='productName'>按名称搜索</Option>
          <Option value='productDesc'>按描述搜索</Option>
        </Select>
        <Input placeholder='关键字' style={{width:150, margin: '0 10px'}} 
        value= {searchName}
        onChange={event => this.setState ({searchName: event.target.value})}/>
        <Button type="primary" onClick={()=>{this.getProductList()}}>搜索</Button>
      </div>
    )

    const extra = (
      <Button type="primary" icon={<PlusCircleOutlined />} onClick={()=> {this.props.navigate('addupdate')}}>添加商品</Button>
    )
    

    return (
      <Card
      title={title}
      extra={extra}
      style={{
        width: '100%',
      }}
    >
     <Table 
     sticky 
     bordered 
     loading={loading}
     rowKey= '_id' 
     dataSource={products} 
     columns={this.columns}
     pagination={{total, defaultPageSize: 3,showQuickJumper: true, onChange: this.getProductList }}
      />
    </Card>
    );
  }
}

export default withRouter(ProductHome);
